package org.atlantis.grosbeak.logger.adapter;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

/**
 * Log4j的日志实现。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
class Log4jLogger extends BaseLogger {

	private Logger logger;

	// Log4j 1.2.11之前版本不支持Trace级别，默认采用Debug来输出。
	private boolean supportTrace = true;

	Log4jLogger() {
		logger = LogManager.getRootLogger();
		loadLevel();
	}

	Log4jLogger(String className) {
		logger = LogManager.getLogger(className);
		loadLevel();
	}

	private void loadLevel() {
		isFatalEnabled = logger.isEnabledFor(Level.FATAL);
		isErrorEnabled = logger.isEnabledFor(Level.ERROR);
		isWarnEnabled = logger.isEnabledFor(Level.WARN);
		isInfoEnabled = logger.isEnabledFor(Level.INFO);
		isDebugEnabled = logger.isEnabledFor(Level.DEBUG);
		try {
			isTraceEnabled = logger.isEnabledFor(Level.TRACE);
		} catch (Throwable e) {
			isTraceEnabled = false;
			supportTrace = false;
		}
	}

	public void debug(Object message, Throwable cause) {
		if (isDebugEnabled())
			logMessage(Level.DEBUG, message, cause);

	}

	public void error(Object message, Throwable cause) {
		if (isErrorEnabled())
			logMessage(Level.ERROR, message, cause);
	}

	public void fatal(Object message, Throwable cause) {
		if (isFatalEnabled())
			logMessage(Level.FATAL, message, cause);
	}

	public void info(Object message, Throwable cause) {
		if (isInfoEnabled())
			logMessage(Level.INFO, message, cause);
	}

	public void trace(Object message, Throwable cause) {
		if (isTraceEnabled())
			logMessage(Level.TRACE, message, cause);
		else if (!supportTrace)
			debug(message, cause);
	}

	public void warn(Object message, Throwable cause) {
		if (isWarnEnabled())
			logMessage(Level.WARN, message, cause);
	}

	private void logMessage(Priority priority, Object message, Throwable cause) {
		if (cause != null)
			logger.log(priority, message, cause);
		else
			logger.log(priority, message);
	}
}
